<?php
/**
 * User: xzq
 * Date: 2018/8/7
 * Time: 17:17
 */
namespace app\common\util\applet;
use app\common\controller\Common;
use think\Db;
class Generate extends Common
{
    private $appid = '';
    private $appSecret = '';
    public function _initialize(){
        $this->appid = config('module_wechat.appid');
        $this->appSecret = config('module_wechat.appsecret');
    }

    /**
     * 发送模板信息
     * @param $type 发送类型
     * @param $openid openid
     * @param $formidStr formid集合
     * @param $stime 预约开始时间
     * @param $etime  预约结束时间
     * @param $addr  预约地址
     * @return string
     */
    public function sendInfo($type,$openid,$formidStr,$stime,$etime,$addr){
        $violationNum = config('module_library.violation_num');
        $yyid = config('module_wechat.yy_code');
        $qdid = config('module_wechat.qd_code');
        $qtid = config('module_wechat.qt_code');
        $formidarr = explode('|',$formidStr);
        if ($type == 1){
            $formid = $formidarr[0];
            $stime = date('Y-m-d H:i',$stime);
            $etime = date('Y-m-d H:i',$etime);
        }elseif ($type == 2){
            $formid = $formidarr[1];
            $qdtime = date('Y-m-d H:i',$stime+20*60);
            $description = '超出时间未签到，将自动判定违规,违规超过'.$violationNum.'次，将自动封号';
        }else{
            $formid = $formidarr[2];
            $qttime = date('Y-m-d H:i',$etime+10*60);
            $description = '超出时间未签退，将自动判定违规,违规超过'.$violationNum.'次，将自动封号';
        }
        $library = '图书馆选座';
        if ($type==1) {
            $json=<<<yy
{
	"touser":"$openid",
	"template_id":"$yyid",
	"page":"pages/home",
	"form_id":"$formid",
	"data": {
		"keyword1": {
			"value": "$library",
			"color": "#666666"
		},
		"keyword2": {
			"value":"$stime",
			"color":"#666666"
		},
		"keyword3": {
			"value": "$etime",
			"color":"#666666"
		},
		"keyword4": {
			"value":"$addr",
			"color":"#666666"
		}
	},
	"emphasis_keyword":""
}
yy;
        }elseif($type == 2){
            $json=<<<qd
{
	"touser":"$openid",
	"template_id":"$qdid",
	"page":"pages/home",
	"form_id":"$formid",
	"data": {
		"keyword1": {
			"value": "$library",
			"color": "#666666" 
		},
		"keyword2": {
			"value": "$addr",
			"color": "#666666" 
		},
		"keyword3": { 
			"value": "$qdtime", 
			"color": "#666666" 
		} ,
		"keyword4": { 
			"value": "$description", 
			"color": "#666666" 
		} 
	}, 
	"emphasis_keyword": ""
} 
qd;
        }else{
            $json=<<<qt
{
	"touser":"$openid",
	"template_id":"$qtid",
	"page":"pages/home",
	"form_id":"$formid",
	"data": {
		"keyword1": {
			"value": "$library",
			"color": "#666666" 
		},
		"keyword2": {
			"value": "$addr",
			"color": "#666666" 
		},
		"keyword3": { 
			"value": "$qttime", 
			"color": "#666666" 
		} ,
		"keyword4": { 
			"value": "$description", 
			"color": "#666666" 
		} 
	}, 
	"emphasis_keyword": ""
} 
qt;
        }
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$accessToken;
        return $res=$this->curl($url,$json);
    }
    /**
     * 生成二维码
     * @param array $map
     * @return mixed
     */
    public function code($map=[]){
        $areaid = $map['areaid'];
        $num = $map['seatNum'];
        $title = $map['areaname'];
        unset($map['areaname']);
        $res = Db::name('code')->field('code')->where($map)->find();
        $savePath = 'upload/code/'.date('Ymd').'/';
        $path = ROOT_PATH.$savePath;
        is_dir($path) OR mkdir($path, 0777, true);
        $scene = $areaid.'&'.$num;
        if (!empty($res['code'])) {
            return $this->show(1,'success',$res['code']);
        }else{
            $accessToken = $this->getAccessToken();
            $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
            $fileds=json_encode(['scene'=>$scene,'page'=>"pages/scan/scan",'width'=>430],JSON_UNESCAPED_UNICODE);
            $ojb=$this->curl($url,$fileds);
            $name = time().rand(1000,9999).'.jpg';
            $codeimg = $path.$name;
            file_put_contents($codeimg,$ojb);
            $code = $this->merge($path,$savePath,$codeimg,$title,$num,$areaid);
            $map['code'] = $code['data'];
            $map['ctime'] = time();
            Db::name('code')->insert($map);
            return $code;
        }
    }

    /**
     * 图片合成
     * @param $code
     * @param $title
     * @param $num
     * @return string
     */
    function merge($path,$savePath,$code,$title,$num,$areaid){
        $width = 550;
        $height = 690;
        $fontpath = ROOT_PATH.'static/code_font/';
        $filepath = $path;
        $fielname=time().'_'.$areaid.'_'.$num.'.jpg';
        if (!file_exists($code)) {
            return $this->show(0,'二维码图片不存在!');
        }
        $target_img = imagecreatetruecolor($width,$height);
        $code = @imagecreatefromjpeg($code);
        if (!$code) {
            return $this->show(0,'二维码生成失败!');
        }
        // 颜色
        $white = imagecolorallocate($target_img, 255, 255, 255);
        $black = imagecolorallocate($target_img, 0, 0, 0);
        imagefill($target_img, 0, 0, $white);
        //拷贝二维码
        imagecopy($target_img,$code,60,60,0,0,430,430);
        //标题文字
        $tit_x = ($width-(strlen($title)/3)*24*1.52)/2;
        $tit_y = $width;
        imagettftext($target_img,24,0,$tit_x,$tit_y,$black,$fontpath.'pf_x.ttf',$title);
        $num = '编号:'.$num;
        $num_x = ($width-(strlen($num)/3)*32*1.58)/2;
        $num_y = $width+80;
        imagettftext($target_img,32,0,$num_x,$num_y,$black,$fontpath.'pf_c.ttf',$num);
        imagejpeg($target_img,$filepath.$fielname);
        imagedestroy($target_img);
        imagedestroy($code);
        return $this->show(1,'success','/'.$savePath.$fielname);
    }
    /**
     * 获取access_token
     * @return bool
     */
    public function getAccessToken(){
        //缓存文件
        $cacheName=md5($this->appid.$this->appSecret);
        $file=__DIR__.'/'.$cacheName.'.php';
        if ( is_file($file) && filemtime($file)+7000 > time() ) {
            //缓存有效
            $data = include $file;
            $accessToken =$data['access_token'];
        }else{
            $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appSecret;
            $data=$this->curl($url);
            $data=json_decode($data,TRUE);
            //获取access_token失败
            if (isset($data['errcode'])) {
                return false;
            }
            $accessToken=$data['access_token'];
            //缓存access_token
            file_put_contents($file, '<?php return '.var_export($data,TRUE).';?>');
        }
        return $accessToken;
    }
    //使用curl 发送get/post请求 $fileds存在就是post请求
    public function curl($url,$fileds=''){
        $ch = curl_init();
        //设置我们请求的地址
        curl_setopt($ch, CURLOPT_URL, $url);
        //数据返回不要直接显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //禁止证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($fileds) {
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fileds);
        }

        $data='';
        if (curl_exec($ch)) {
            //如果发送成功,获取数据
            $data=curl_multi_getcontent($ch);
        }
        curl_close($ch);
        return $data;
    }
    //数据返回格式
    function show($code, $message, $arr = []){
        $data['code'] = $code;
        $data['msg'] = $message;
        $data['data'] = $arr;
        return $data;
    }
}